package com.lovi.net_;


import com.lovi.utils.StreamUtils;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 下载文件服务端
 * 接受客户端发过来要下载的文件
 *
 */
public class DownLoadFileServer {
    public static void main(String[] args) throws IOException {
        //1. 接收用户发过来的要下载的文件名
        //先进行端口监听
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端端正在监听，等待用户发送要下载的文件...");
        Socket socket = serverSocket.accept();
        //接收到用户发过来的文件名
        String fileName = "";
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = is.read(bytes)) != -1){
            fileName += new String(bytes,0,len);
        }
        System.out.println("用户要下载的文件名为：" + fileName);
        String filePath = "";
        if ("大艺术家".equals(fileName)){
            filePath = "D:\\桌面\\test"+"\\大艺术家.txt";
        }else {
            filePath = "D:\\桌面\\test"+"\\默认返回文件.txt";
        }
        //把文件返回给客户端
        //先拿到我呢间
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        byte[] bytes1 = StreamUtils.streamToBytes(new FileInputStream(filePath));
        bos.write(bytes1);
        bos.flush();
        socket.shutdownOutput();
        //关闭资源
        bos.close();
        is.close();
        System.out.println("服务端退出...");

    }
}
